﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using eLearning.Util;

namespace eLearning.DosenView
{
    public partial class TugasFormPage : PhoneApplicationPage
    {
        private Tugas tugas;
        private bool firstLoaded;

        public TugasFormPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
            {
                firstLoaded = false;
            }
            else
            {
                firstLoaded = true;
            }
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (firstLoaded)
            {
                if (PhoneApplicationService.Current.State.ContainsKey(Config.TUGAS))
                {
                    tugas = (Tugas)PhoneApplicationService.Current.State[Config.TUGAS];
                    if (tugas.Id != null)
                    {
                        textBoxJudul.Text = tugas.Judul;
                        textBoxDeskripsi.Text = tugas.Deskripsi;
                        datePickerStart.Value = tugas.Awal;
                        datePickerEnd.Value = tugas.Akhir;
                        if (tugas.DetMatkul.Id != null)
                            textPerkuliahan.Text = "Tugas " + tugas.DetMatkul.Matkul.Nama;
                        if (tugas.DetMatkul.Creator == null)
                        {
                            textBlockMatkul.Visibility = Visibility.Collapsed;
                            matkulList.Visibility = Visibility.Collapsed;
                        }
                    }
                    else
                    {
                        if (tugas.DetMatkul.Id == null)
                        {
                            textBlockMatkul.Visibility = Visibility.Visible;
                            matkulList.Visibility = Visibility.Visible;
                            textPerkuliahan.Text = "Tugas Baru";
                            LoadPerkuliahan();
                        }
                        else
                        {
                            textBlockMatkul.Visibility = Visibility.Collapsed;
                            matkulList.Visibility = Visibility.Collapsed;
                        }
                        textBoxJudul.Text = "";
                        textBoxDeskripsi.Text = "";
                        if (tugas.DetMatkul.Id != null)
                            textPerkuliahan.Text = "Tugas " + tugas.DetMatkul.Matkul.Nama;
                    }
                }
            }
        }

        private void LoadPerkuliahan()
        {
            DetailMatkul kuliah = new DetailMatkul();
            kuliah.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();
            string json = JsonConvert.SerializeObject(kuliah);

            string url = Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.PERKULIAHAN_DOSEN_VIEW_KEY;

            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listPerkuliahan_UploadStringCompleted);
            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void listPerkuliahan_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                DetailMatkulList list = JsonConvert.DeserializeObject<DetailMatkulList>(e.Result);
                matkulList.ItemsSource = list;
                if (tugas.DetMatkul.Matkul != null)
                    matkulList.SelectedItem = tugas.DetMatkul.Matkul;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void SaveTugas(Tugas data)
        {
            string json = null, url = null;


            if (data.Id == null)
            {
                url = Config.Instance.TUGAS_SERVICE_URL() + Config.ADD_ACTION_KEY; //create
            }
            else
            {
                url = Config.Instance.TUGAS_SERVICE_URL() + Config.UPDATE_ACTION_KEY; //update
            }
            json = JsonConvert.SerializeObject(data);


            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(saveChange_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void saveChange_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                    return;

                MessageBox.Show("Message : " + e.Result);

                if (e.Result.Contains("Success"))
                    NavigationService.GoBack();

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void buttonSave_Click(object sender, System.EventArgs e)
        {
            if (matkulList.Visibility == Visibility.Visible)
                tugas.DetMatkul = (DetailMatkul)matkulList.SelectedItem;
            tugas.Judul = textBoxJudul.Text;
            tugas.Deskripsi = textBoxDeskripsi.Text;
            tugas.Awal = datePickerStart.Value.Value;
            tugas.Akhir = datePickerEnd.Value.Value;

            SaveTugas(tugas);
        }

        private void buttonCancel_Click(object sender, System.EventArgs e)
        {
            NavigationService.GoBack();
        }

    }
}